<?php

namespace App\Service;
use App\Model\BaseBanner;
use App\Common\Response\SystemCode;
use App\Model\DataOrderPlaylet;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use App\Model\PlayletRanking;
use App\Model\PlayletTag;
use App\Model\Tag;
use App\Model\DataUser;
use Hyperf\DbConnection\Db;

class HomeService extends CommicService
{
    const STATUS_ENABLE  = 1;
    public function index($userId=0){

        $newData = array();
        $oldData = array();
        $newplayletIds = PlayletTag::query()->where(['tag_id' => 51])->pluck('playlet_id');
        $newtList = Playlet::query()->whereIn('id',$newplayletIds)
            ->where('status',Playlet::STATUS_SHOW)
            ->select('id','is_finish','name','cover','price','introduction','pay_type','created_at','rank')->limit(12)->orderBy('rank','desc')->get();
        foreach ($newtList as $newItem){

            $count = PlayletEpisodes::query()->where(['playlet_id' => $newItem['id']])->count();
            if($newItem['is_finish'] == 1){
                $newItem['episodes_name'] = $count.'集全';
            }else{
                $newItem['episodes_name'] = '更新至'.$count.'集';
            }
            $newItem['is_buy'] = false;
//            if(!empty($userId)){
//
//                $dataOrder =DataOrderPlaylet::query()->where(['playlet_id' => $newItem['id'],'data_user_id' => $userId])->exists();
//
//                if($dataOrder){
//                    $newItem['is_buy'] = true;
//                }
//            }

            $newData[] = $newItem;
        }
        $oldplayletIds = PlayletTag::query()->where(['tag_id' => 52])->pluck('playlet_id');
        $oldList = Playlet::query()->whereIn('id',$oldplayletIds)
            ->where('status',Playlet::STATUS_SHOW)
            ->select('id','is_finish','name','cover','price','introduction','pay_type','created_at','rank')->limit(12)->orderBy('rank','desc')->get();
        foreach ($oldList as $oldItem){
            $count = PlayletEpisodes::query()->where(['playlet_id' => $oldItem['id']])->count();
            if($oldItem['is_finish'] == 1){

                $oldItem['episodes_name'] = $count.'集全';
            }else{
                $oldItem['episodes_name'] = '更新至'.$count.'集';
            }
            $oldItem['is_buy'] = false;
//            if(!empty($userId)){
//                $dataOrder =DataOrderPlaylet::query()->where(['playlet_id' => $oldItem['id'],'data_user_id' => $userId])->exists();
//                if($dataOrder){
//                    $oldItem['is_buy'] = true;
//                }
//            }
            $oldData[] = $oldItem;
        }
        $data['newData'] = $newData;
        $data['oldData'] = $oldData;

        $homeList = array_merge_recursive($newData,$oldData);
        $homeList = array_values($homeList);
        array_multisort(array_column($homeList,'rank'),SORT_DESC,$homeList);
        $data['homeList'] = $homeList;
        return $data;
    }
    public function tag(){

        $tagRes = Tag::query()->select(['id','name'])->where(['parent_id'=> 0])->orderBy('sort','desc')->get();
        $resultData = array();
        foreach ($tagRes as $tag){
            $tagInfo = $tag->toArray();
            $tagInfo['children'] = Tag::query()->select(['id as value','name as label'])->where(['parent_id'=> $tag->id])->orderBy('sort','desc')->get();
            $resultData[] = $tagInfo;
        }
        return $resultData;
    }
    public function list(Array $params,$userId = 0){

        $tagIds      = $params['tag_ids'] ?? '';
        $pageSize    = $params['pageSize'] ?? 12;
        $page        = $params['page'] ?? 1;
        $playletIds = array();
        $is_selcet = false;
        if ($tagIds) {
            $is_selcet = true;
            $playletIds = PlayletTag::select()->whereIn('tag_id',$tagIds)->pluck('playlet_id')->toArray();
            //获取重复的短剧ID
            if(count($tagIds) > 1){
                $playletCount = array_count_values($playletIds);
                $playletIds = array();

                foreach ($playletCount as $key => $item){
                    if($item >= count($tagIds)){
                        $playletIds[] = $key;
                    }
                }
            }
        }
        $query = Playlet::query()->select('id','is_finish','name','cover','price','introduction','pay_type','created_at');
        if (!empty($playletIds)) {
            $query->whereIn('id',$playletIds);
        }else{
            if($is_selcet){
                $query->where(['id' => 0]);
            }
        }
        $models = $query->where('status',Playlet::STATUS_SHOW)->orderBy('rank','desc')->orderBy('id','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            if($data['is_finish'] == 1){
                $count = PlayletEpisodes::query()->where(['playlet_id' => $data['id']])->count();
                $data['episodes_name'] = $count.'集全';
            }else{
                $playlet_number = PlayletEpisodes::query()->where(['playlet_id' => $data['id']])->orderBy('playlet_number','desc')->value('playlet_number');
                $data['episodes_name'] = '更新至'.($playlet_number ?? 0).'集';
            }
//            $data['is_buy'] = false;
//            if(!empty($userId)){
//
//                $dataOrder =DataOrderPlaylet::query()->where(['playlet_id' => $item->id,'data_user_id' => $userId])->exists();
//
//                if($dataOrder){
//                    $data['is_buy'] = true;
//                }
//            }

            $selectData[] =$data;
        }
        $data = $models->toArray();
        $data['data'] = $selectData;
        return $data;
    }
    public function episodes($id){
        $playletInfo = Playlet::query()->select(['id','name','price','introduction','cover','is_finish','pay_type','created_at','updated_at'])->where(['status' => Playlet::STATUS_SHOW])->where('id', $id)->first();
        $playletEpisodesInfo = array();
        if(!empty($playletInfo)){
            $playletEpisodesInfo = PlayletEpisodes::query()->select(['playlet_number','playlet_number_name','play_url','cover'])->where(['playlet_id' => $id])->orderBy('playlet_number','asc')->get();
            $count = count($playletEpisodesInfo);
            if($playletInfo->is_finish == 1){
                $playletInfo->episodes_name = $count.'集全';
            }else{
                $playlet_number = 0;
                if($count > 0){
                    $playlet_number = $playletEpisodesInfo[$count-1]->playlet_number;
                }

                $playletInfo->episodes_name = '更新至'.$playlet_number.'集';
            }
        }

        $data['playlet'] = $playletInfo;
        $data['episodes'] = $playletEpisodesInfo;
        return $data;
    }

    public function setUser($access_token,$userInfo){

        $redisKey = 'web_dataUserInfo:'.$access_token;
        $this->redisService->setex($redisKey,14400,json_encode($userInfo));
    }

    public function delUser($access_token){

        $this->redisService->del('web_dataUserInfo:'.$access_token);
    }
    public function getUser($access_token){

        return  $this->redisService->get('web_dataUserInfo:'.$access_token);
    }

    public function generateToken(string $username)
    {
        $this->access_token = md5($username . time() . rand(1000, 9999));
        $this->expire_in = time()+ 14400;
        return [
            'access_token' => $this->access_token,
            'expire_in'    => $this->expire_in,
        ];
    }
    public function checkUser(string $username,string $password){

        $userInfo =  DataUser::query()->where('username',$username)->select('id','username','access_token','password','real_name')
            ->first();
        if(empty($userInfo)){
            return false;
        }
        $password = md5($password);
        if($userInfo->password != $password){
            return false;
        }

        return $userInfo;
    }
}